import { defineStore } from 'pinia'

const AUTH_PERSIST_KEY = 'auth'

// 动态存储适配器
class DynamicStorage {
  constructor() {
    // 智能检测存储类型：优先检查localStorage中是否有数据
    this.currentType = this.detectStorageType() || 'session'
  }
  
  // 检测应该使用哪种存储类型
  detectStorageType() {
    try {
      // 检查localStorage中是否有auth数据
      const localData = localStorage.getItem(AUTH_PERSIST_KEY)
      if (localData && localData !== 'null' && localData !== '{}') {
        const parsed = JSON.parse(localData)
        // 如果localStorage中有有效的access或refresh token，使用localStorage
        if (parsed && (parsed.access || parsed.refresh)) {
          return 'local'
        }
      }
      
      // 检查sessionStorage中是否有auth数据
      const sessionData = sessionStorage.getItem(AUTH_PERSIST_KEY)
      if (sessionData && sessionData !== 'null' && sessionData !== '{}') {
        const parsed = JSON.parse(sessionData)
        // 如果sessionStorage中有有效的access或refresh token，使用sessionStorage
        if (parsed && (parsed.access || parsed.refresh)) {
          return 'session'
        }
      }
    } catch (error) {
      console.warn('检测存储类型时出错:', error)
    }
    
    // 默认返回null，让构造函数使用默认的'session'
    return null
  }
  
  setType(type) {
    this.currentType = type
  }
  
  getItem(key) {
    const storage = this.currentType === 'local' ? localStorage : sessionStorage
    return storage.getItem(key)
  }
  
  setItem(key, value) {
    const storage = this.currentType === 'local' ? localStorage : sessionStorage
    storage.setItem(key, value)
  }
  
  removeItem(key) {
    const storage = this.currentType === 'local' ? localStorage : sessionStorage
    storage.removeItem(key)
  }
}

// 创建动态存储实例
const dynamicStorage = new DynamicStorage()

export const useAuthStore = defineStore('auth', {
  state: () => ({
    access: '',
    refresh: '',
    username: '',
    storageType: dynamicStorage.currentType // 使用动态存储的当前类型
  }),

  actions: {
    setTokens({ access, refresh }) {
      if (typeof access === 'string') this.access = access
      if (typeof refresh === 'string') this.refresh = refresh
    },
    setUsername(name) {
      this.username = name || ''
    },
    clear() {
      this.access = ''
      this.refresh = ''
      this.username = ''
    },

    switchStorageType(type) {
      if (type !== 'local' && type !== 'session') return
      if (type === this.storageType) return

      // 清除旧位置的数据
      const oldStorage = this.storageType === 'local' ? localStorage : sessionStorage
      oldStorage.removeItem(AUTH_PERSIST_KEY)

      // 更新存储类型
      this.storageType = type
      dynamicStorage.setType(type)
    },

    // 新增：获取当前实际使用的存储类型
    getCurrentStorageType() {
      return dynamicStorage.currentType
    }
  },

  persist: 
  [
	{
		key: AUTH_PERSIST_KEY,
		paths: ['access', 'refresh', 'username'],
		storage: dynamicStorage
	}
] 
//   {
	
//     strategies: [
//       {
//         key: AUTH_PERSIST_KEY,
//         storage: dynamicStorage,
//         paths: ['access', 'refresh', 'username']
//       }
//     ]
//   }
})

export default useAuthStore